<?php

class SJB_Admin_Miscellaneous_Plugins extends SJB_Function
{
	public function isAccessible()
	{
		$plugin = SJB_Request::getVar('plugin', null);
		switch ($plugin) {
			case 'PhpBBBridgePlugin':
				$this->setPermissionLabel('set_phpbb_plug-in');
				break;
			case 'LinkedinSocialPlugin':
				$this->setPermissionLabel('set_linkedin_plug-in');
				break;
			case 'FacebookSocialPlugin':
				$this->setPermissionLabel('set_facebook_plug-in');
				break;
			case 'WordPressBridgePlugin':
				$this->setPermissionLabel('set_wordpress_plug-in');
				break;
			case 'TwitterIntegrationPlugin':
				$this->setPermissionLabel('set_twitter_plug-in');
				break;
			case 'ShareThisPlugin':
				$this->setPermissionLabel('set_sharethisplugin');
				break;
			case 'CaptchaPlugin':
				$this->setPermissionLabel('set_captchaplugin');
				break;
			case 'IndeedPlugin':
				$this->setPermissionLabel('set_indeedplugin');
				break;
			case 'SimplyHiredPlugin':
				$this->setPermissionLabel('set_simplyhiredplugin');
				break;
			case 'GoogleSocialPlugin':
				$this->setPermissionLabel('set_googleplugin');
				break;
			case 'GoogleAnalyticsPlugin':
				$this->setPermissionLabel('set_googleanalyticsplugin');
				break;
			case 'BeyondPlugin':
				$this->setPermissionLabel('set_beyondplugin');
				break;

			default:
				$this->setPermissionLabel(
					array(
						'manage_plug-ins',
						'set_phpbb_plug-in',
						'set_linkedin_plug-in',
						'set_facebook_plug-in',
						'set_wordpress_plug-in',
						'set_twitter_plug-in',
						'set_sharethisplugin',
						'set_captchaplugin',
						'set_indeedplugin',
						'set_simplyhiredplugin',
						'set_googleplugin',
						'set_googleanalyticsplugin',
						'set_beyondplugin',
					)
				);
				break;
		}
		return parent::isAccessible();
	}

	public function execute()
	{
		$tp = SJB_System::getTemplateProcessor();

		$saved = false;
		$action = SJB_Request::getVar('action');
		$form_submitted = SJB_Request::getVar('submit');
		$template = 'plugins.tpl';
		$errors = array();
		if (SJB_Request::getVar('error', false))
			$errors[] = SJB_Request::getVar('error', false);
		$messages = array();
		if (SJB_Request::getVar('message', false))
			$messages[] = SJB_Request::getVar('message', false);

		switch ($action) {
			case 'grant_twitter_permission':
				$feedInfo = SJB_Twitter::getFeedInfoBySID(SJB_Request::getVar('sid'));
				$config = array(
					'callbackUrl' => SJB_System::getSystemSettings('SITE_URL') . '/system/miscellaneous/plugins/?action=grant_twitter_permission&sid=' . SJB_Request::getVar('sid', '') . '&plugin=TwitterIntegrationPlugin&process_token=1',
					'siteUrl' => 'http://twitter.com/oauth',
					'consumerKey' => $feedInfo['consumerKey'],
					'consumerSecret' => $feedInfo['consumerSecret'],
					'requestTokenUrl' => 'https://api.twitter.com/oauth/request_token',
					'userAuthorisationUrl' => 'https://api.twitter.com/oauth/authorize',
					'accessTokenUrl' => 'https://api.twitter.com/oauth/access_token',
				);

				$consumer = new Zend_Oauth_Consumer($config);
				$client = new Zend_Http_Client();
				$client->setConfig(array('sslcert' => '../../plugins/twitter_integration_plugin/cacert.pem'));
				$consumer->setHttpClient($client);

				$sessionTwitterRequestToken = SJB_Session::getValue('TWITTER_REQUEST_TOKEN');
				if (SJB_Request::getVar('process_token', false) && !is_null($sessionTwitterRequestToken)) {
					try {
						$accessToken = $consumer->getAccessToken($_GET, unserialize($sessionTwitterRequestToken));
						$feedInfo['access_token'] = $accessToken;
						$twitter = TwitterIntegrationPlugin::getZendServiceTwitter($feedInfo, $accessToken);

						$response = $twitter->account->accountVerifyCredentials()->toValue();

						if (!empty($response->screen_name) && $response->screen_name == $feedInfo['username']) {
							SJB_Twitter::updateFeedToken(SJB_Request::getVar('sid'), $accessToken);
							SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/system/miscellaneous/plugins/?action=settings&plugin=TwitterIntegrationPlugin&message=' . urlencode('Twitter account successfully updated'));
						}
						else {
							SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/system/miscellaneous/plugins/?action=settings&plugin=TwitterIntegrationPlugin&error=' . urlencode('Twitter account verification failed'));
						}
					} catch (Exception $ex) {
						SJB_Error::writeToLog($ex->getMessage());
						$errors[] = 'Twitter account update failed';
					}
				}
				else {
					try {
						$requestToken = $consumer->getRequestToken();
						SJB_Session::setValue('TWITTER_REQUEST_TOKEN', serialize($requestToken));
						$consumer->redirect();
					} catch (Exception $ex) {
						SJB_Error::writeToLog($ex->getMessage());
						SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/system/miscellaneous/plugins/?action=settings&plugin=TwitterIntegrationPlugin&error=' . urlencode('Could not retrieve a valid Token. Please check "Consumer Key" and "Consumer secret"'));
					}
				}
				break;

			case 'save':
				$paths = SJB_Request::getVar('path');
				$active = SJB_Request::getVar('active');
				$subAdminSID = SJB_SubAdmin::getSubAdminSID();
				if (SJB_System::getSystemSettings('isDemo'))
					$errors[] = 'You don\'t have permissions for it. This is a Demo version of the software.';
				else {
					foreach ($paths as $key => $path) {
						$config = SJB_PluginManager::getPluginConfigFromIniFile($path);
						// check subadmins permissions
						if ($subAdminSID) {
							switch ($key) {
								case 'FacebookSocialPlugin':
									if (!$this->acl->isAllowed('set_facebook_plug-in', $subAdminSID))
										continue(2);
									break;
								case 'LinkedinSocialPlugin':
									if (!$this->acl->isAllowed('set_linkedin_plug-in', $subAdminSID))
										continue(2);
									break;
								case 'PhpBBBridgePlugin':
									if (!$this->acl->isAllowed('set_phpbb_plug-in', $subAdminSID))
										continue(2);
									break;
								case 'TwitterIntegrationPlugin':
									if (!$this->acl->isAllowed('set_twitter_plug-in', $subAdminSID))
										continue(2);
									break;
								case 'WordPressBridgePlugin':
									if (!$this->acl->isAllowed('set_wordpress_plug-in', $subAdminSID))
										continue(2);
									break;
								case 'ShareThisPlugin':
									if (!$this->acl->isAllowed('set_sharethisplugin', $subAdminSID))
										continue(2);
									break;
								case 'CaptchaPlugin':
									if (!$this->acl->isAllowed('set_captchaplugin', $subAdminSID))
										continue(2);
									break;
								case 'IndeedPlugin':
									if (!$this->acl->isAllowed('set_indeedplugin', $subAdminSID))
										continue(2);
									break;
								case 'SimplyHiredPlugin':
									if (!$this->acl->isAllowed('set_simplyhiredplugin', $subAdminSID))
										continue(2);
									break;
								case 'GoogleSocialPlugin':
									if (!$this->acl->isAllowed('set_googleplugin', $subAdminSID))
										continue(2);
									break;
								case 'GoogleAnalyticsPlugin':
									if (!$this->acl->isAllowed('set_googleanalyticsplugin', $subAdminSID))
										continue(2);
									break;
								case 'BeyondPlugin':
									if (!$this->acl->isAllowed('set_beyondplugin', $subAdminSID))
										continue(2);
									break;
							}
						}
						$config['active'] = $active[$key];
						$saved = SJB_PluginManager::savePluginConfigIntoIniFile($path, $config);
						if (!$saved)
							$errors[] = 'Failed to save ' . $key . ' settings';
					}
				}
				SJB_PluginManager::reloadPlugins();
				break;

			case 'save_settings':
				$request = $_REQUEST;
				$request = self::checkRequiredFields($request);
				if (!isset($request['setting_errors'])) {
					SJB_Settings::updateSettings($request);
					if ($form_submitted == 'save') {
						break;
					} else if ($form_submitted == 'apply') {
						$pluginName = SJB_Request::getVar('plugin');
						SJB_HelperFunctions::redirect('?action=settings&plugin=' . $pluginName);
					}
				}
				else {
					unset($request['setting_errors']);
					$errors = $request;
				}

			case 'settings':
				$pluginName = SJB_Request::getVar('plugin');
				$plugin = SJB_PluginManager::getPluginByName($pluginName);
				if (isset($plugin['name'])) {
					$pluginObj = new $plugin['name'];
					$settings = $pluginObj->pluginSettings();
					$template = 'plugin_settings.tpl';
					$tp->assign('plugin', $plugin);
					SJB_Event::dispatch('RedefineTemplateName', $template, true);
					$tp->assign('settings', $settings);
					if ($pluginName != 'TwitterIntegrationPlugin') {
						$savedSettings = SJB_Settings::getSettings();
						SJB_Event::dispatch('RedefineSavedSetting', $savedSettings, true);
						$tp->assign('savedSettings', $savedSettings);
					}
				}
				break;

			case 'add_feed':
				$pluginName = SJB_Request::getVar('plugin');
				$plugin = SJB_PluginManager::getPluginByName($pluginName);
				$pluginObj = new $plugin['name'];
				$feed = $pluginObj->twitterFeed();
				$add_form = new SJB_Form($feed);
				$add_form->registerTags($tp);
				$form_fields = $add_form->getFormFieldsInfo();
				$search_form_builder = new SJB_SearchFormBuilder($feed);
				$criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($_REQUEST);
				$search_form_builder->setCriteria($criteria);
				$search_form_builder->registerTags($tp);
				$listingFields = $feed->common_fields;

				$tp->assign('plugin', $plugin);
				$tp->assign('form_fields', $form_fields);
				$tp->assign('listingFields', $listingFields);
				$tp->assign('action', $action);
				$template = 'twitter_input_form.tpl';
				break;

			case 'edit_feed':
				$sid = SJB_Request::getVar('sid');
				if ($sid) {
					$pluginName = SJB_Request::getVar('plugin');
					$plugin = SJB_PluginManager::getPluginByName($pluginName);
					$pluginObj = new $plugin['name'];
					$feed_info = $pluginObj->getFeedInfoBySID($sid);
					$feed_info = array_merge($feed_info, $_REQUEST);
					$criteriaInfo = $feed_info['search_data'] ? unserialize($feed_info['search_data']) : '';
					$feed = $pluginObj->twitterFeed($feed_info);
					$add_form = new SJB_Form($feed);
					$add_form->registerTags($tp);
					$form_fields = $add_form->getFormFieldsInfo();
					$search_form_builder = new SJB_SearchFormBuilder($feed);
					$criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($criteriaInfo);
					$search_form_builder->setCriteria($criteria);
					$search_form_builder->registerTags($tp);
					$listingFields = $feed->common_fields;
					$tp->assign('plugin', $plugin);
					$tp->assign('feed_sid', $sid);
					$tp->assign('form_fields', $form_fields);
					$tp->assign('listingFields', $listingFields);
					$tp->assign('action', $action);
					$template = 'twitter_input_form.tpl';
				}
				break;

			case 'save_feed':
				$sid = SJB_Request::getVar('sid');
				$action_feed = SJB_Request::getVar('action_feed');
				$field_errors = array();
				$pluginName = SJB_Request::getVar('plugin');
				$plugin = SJB_PluginManager::getPluginByName($pluginName);
				$pluginObj = new $plugin['name'];
				$feed = $pluginObj->twitterFeed($_REQUEST);
				if ($sid) {
					$feed->setSID($sid);
					$tp->assign('feed_sid', $sid);
				}
				$criteria_saver = new SJB_ListingCriteriaSaver();
				$criteria_saver->setSessionForCriteria($_REQUEST);
				$requested_data = $criteria_saver->getCriteria();

				$search_form_builder = new SJB_SearchFormBuilder($feed);
				$criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($_REQUEST);
				$search_form_builder->setCriteria($criteria);
				$search_form_builder->registerTags($tp);

				$properties = $feed->getProperties();

				foreach ($properties as $key => $property) {
					if (!$property->isSystem())
						$feed->deleteProperty($key);
				}
				$add_form = new SJB_Form($feed);
				$add_form->registerTags($tp);

				if ($add_form->isDataValid($field_errors)) {
					$feed->addProperty(
						array('id' => 'search_data',
							'type' => 'text',
							'value' => serialize($requested_data),
							'is_system' => true)
					);
					$pluginObj->saveFeed($feed);
					if (empty($sid))
						SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/system/miscellaneous/plugins/?action=grant_twitter_permission&sid=' . $feed->getSID() . '&plugin=TwitterIntegrationPlugin');

					if ($form_submitted == 'save') {
						SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/system/miscellaneous/plugins/?action=settings&plugin=' . $plugin['name']);
					}
				}

				$feed = $pluginObj->twitterFeed($_REQUEST);
				if ($sid) {
					$feed->setSID($sid);
					$tp->assign('feed_sid', $sid);
				}
				$add_form = new SJB_Form($feed);
				$add_form->registerTags($tp);
				$form_fields = $add_form->getFormFieldsInfo();

				$tp->assign('plugin', $plugin);
				$tp->assign('field_errors', $field_errors);
				$tp->assign('form_fields', $form_fields);
				$tp->assign('action', $action_feed);
				$template = 'twitter_input_form.tpl';

				break;

			case 'delete_feed':
				$sid = SJB_Request::getVar('sid');
				if ($sid) {
					$pluginName = SJB_Request::getVar('plugin');
					$plugin = SJB_PluginManager::getPluginByName($pluginName);
					$pluginObj = new $plugin['name'];
					$pluginObj->deleteFeed($sid);
					SJB_HelperFunctions::redirect(SJB_System::getSystemSettings('SITE_URL') . '/system/miscellaneous/plugins/?action=settings&plugin=' . $plugin['name']);
				}
				break;

			case 'editCaptcha':
				$info = $_REQUEST;
				SJB_Event::dispatch('editCaptcha', $info, true);
				foreach ($info as $key => $val) {
					$tp->assign($key, $val);
				}
				$template = $info['template'];
				break;
		}

		$listPlugins = SJB_PluginManager::getAllPluginsList();
		$plugins = array();
		foreach ($listPlugins as $key => $plugin) {
			$group = !empty($plugin['group']) ? $plugin['group'] : 'Common';
			$plugins[$group][$key] = $plugin;
		}
		$tp->assign('saved', $saved);
		$tp->assign('groups', $plugins);
		$tp->assign('errors', $errors);
		$tp->assign('messages', $messages);
		$tp->display($template);
	}

	public static function checkRequiredFields($settings)
	{
		if (isset($settings['plugin'])) {
			$pluginObj      = new $settings['plugin'];
			$settingsFields = $pluginObj->pluginSettings();
			$errors         = array();
			foreach ($settingsFields as $settingsField) {
				if (!empty($settingsField['is_required']) && $settingsField['is_required'] === true && empty($settings[$settingsField['id']])) {
					$errors[$settingsField['caption']] = $settingsField['caption'].' is empty';
				}
				else if (!empty($settingsField['validators'])) {
					foreach ($settingsField['validators'] as $validator) {
						$isValid = $validator::isValid($settings[$settingsField['id']]);
						if ($isValid !== true) {
							$errors[$settingsField['caption']] = $isValid;
						}
					}
				}
			}

			if ($errors) {
				$errors['setting_errors'] = true;
				return $errors;
			}
		}

		return $settings;
	}
}